﻿using System;
using System.Globalization;
using System.IO;
using System.Windows.Controls;

namespace Red.Controls.ValidationRules
{
    public class DirectoryExistsOnDisk : ValidationRule
    {
        public override ValidationResult Validate( object value, CultureInfo cultureInfo )
        {
            string path = (string)value;
            bool directoryExists = Directory.Exists( path );

            if ( directoryExists )
            {
                return new ValidationResult( true, null );
            }

            return new ValidationResult( false, "The specified directory must exist" );
        }
    }

    public class IsValidDrive : ValidationRule
    {
        public override ValidationResult Validate( object value, CultureInfo cultureInfo )
        {
            string path = (string)value;

            if ( string.IsNullOrWhiteSpace( path ) )
            {
                return new ValidationResult( false, "No path specified" );
            }

            string drive;

            try
            {
                drive = Path.GetPathRoot( path );
            }
            catch ( ArgumentException )
            {
                return new ValidationResult( false, "Invalid path" );
            }


            if ( drive.Length > 0 && char.IsLetter( drive[ 0 ] ) )
            {
                try
                {
                    DriveInfo driveInfo = new DriveInfo( drive);

                    switch ( driveInfo.DriveType )
                    {
                        case DriveType.CDRom:
                            return new ValidationResult( false, "Do you seriously expect me to install to an optical disk drive?" );

                        case DriveType.NoRootDirectory:
                            return new ValidationResult( false, "Invalid drive letter specified" );

                    }

                }
                catch ( ArgumentException )
                {
                    return new ValidationResult( false, "Invalid drive letter specified" );
                }
            }

            return new ValidationResult( true, null );
        }
    }
}
